package com.yupi.springbootinit.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * excelUtil工具类
 *
 * 使用 easyExcel
 */
@Slf4j
public class ExcelUtils {

    /**
     * 将excel文件里的表头提取出来，用来生成动态表
     * @param multipartFile
     * @return
     */
    public static List<String> excelGetHeader(MultipartFile multipartFile) {
//        File file = null;
//        try {
//            file = ResourceUtils.getFile("classpath:testData.xlsx");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        List<Map<Integer, String>> list = getMapList(multipartFile);
        //1、判空
        if(CollUtil.isEmpty(list)){
            return Collections.emptyList();
        }
        //2.读取表头
        LinkedHashMap<Integer, String> headerMap = (LinkedHashMap<Integer, String>) list.get(0);
        //2.1过滤表头的空数据
        List<String> headerList = headerMap.values().stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
        return  headerList;
    }

    public static List<List<String>> excelGetData(MultipartFile multipartFile){
//        File file = null;
//        try {
//            file = ResourceUtils.getFile("classpath:testData.xlsx");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        List<Map<Integer, String>> list = getMapList(multipartFile);
        //1、判空
        if(CollUtil.isEmpty(list)){
            return Collections.emptyList();
        }
        //2.0 将每一行的数据（表头下的）拼接成(value1,v2,v3,...)
        List<List<String>> valueList = new LinkedList<>();
        //2.读取数据
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> dataMap = (LinkedHashMap<Integer, String>) list.get(i);
            List<String> dataList = new ArrayList<>(dataMap.values());
            //3.拼接数据
            if(!dataList.isEmpty()) {
                valueList.add(dataList);
            }
        }
        return valueList;
    }

    @Nullable
    private static List<Map<Integer, String>> getMapList(MultipartFile multipartFile) {
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.info("文件读取错误");
            e.printStackTrace();
        }
        return list;
    }


    /**
     * excel 转 csv
     * @param multipartFile
     * @return
     */

    public static String excellToCsv(MultipartFile multipartFile) {
//        File file = null;
//        try {
//            file = ResourceUtils.getFile("classpath:网站数据.xlsx");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        List<Map<Integer, String>> list = getMapList(multipartFile);
        //转换为csv
        //1、判空
        if(CollUtil.isEmpty(list)){
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        //2.读取表头
        LinkedHashMap<Integer, String> headerMap = (LinkedHashMap<Integer, String>) list.get(0);
        //2.1过滤表头的空数据
        List<String> headerList = headerMap.values().stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
        //2.2拼接表头
        stringBuilder.append(StrUtil.join(",",headerList)).append("\n");
        //3.读取数据
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> dataMap = (LinkedHashMap<Integer, String>) list.get(i);
            //3.1过滤数据
            List<String> dataList = dataMap.values().stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
            //3.2拼接数据
            stringBuilder.append(StrUtil.join(",",dataList)).append("\n");
        }
        return stringBuilder.toString();
    }


}
